from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render
from .models import User,Article

# Create your views here.
app_name='article'
def article_test(request):
    user=User(username='test',password='123')
    user.save()
    article=Article(title='Chat新应用',content='test。。。',author=user)
    article.save()
    return HttpResponse('test')

# 获取第一个作者的所有文章
def one_to_many(request):
    user=User.objects.first()
    articles=user.article_set.all()
    for article in articles:
        print(article.title)
    return HttpResponse('查询成功！')

def query1(reqeust):
    article =Article.objects.filter(id__exact=1)
    #查询结果.query看到，article.query，就可以看到底层执行的sql语句
    print(article.query)
    print(article)
    return HttpResponse('查询成功')

def query2(reqeust):
    article =Article.objects.filter(title__exact='chat新应用')
    #查询结果.query看到，article.query，就可以看到底层执行的sql语句
    print(article.query)
    print(article)
    return HttpResponse('查询成功')

def query3(reqeust):
    start_date = datetime(year=2025, month=1, day=1)
    end_date = datetime(year=2025, month=12, day=31)
    article = Article.objects.filter(pub_time__range=(start_date,end_date))
    print(article.query)
    print(article)
    return HttpResponse('查询成功')

def query4(reqeust):
    # 查找标题中，包含t文章的用户
    user = User.objects.filter(articles__title__icontains='t')
    print(user.query)
    print(user)
    return HttpResponse('查询包含xx文章的用户成功')
